package mamikeji.liaowa.ui.fragment.main_date;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MomCircleBean;
import mamikeji.liaowa.bean.Web_Focus;
import mamikeji.liaowa.bean.Web_forum_changeBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.MainActivity;
import mamikeji.liaowa.ui.activity.circle.CircleDetailsActivity;
import mamikeji.liaowa.ui.activity.circle.FriendMSGActivity;
import mamikeji.liaowa.ui.adapter.Main_CircleAdapter;
import mamikeji.liaowa.ui.fragment.BaseFragment;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.main_view.PullLoadMoreRecyclerView;

/**
 * Created by 廉冲-android开发 on 2017/9/13.
 */
public class Main_CircleFragment extends BaseFragment {
    private static final String TAG = "Main_CircleFragment";
    private static final int TAG_CIRCLE = 1001;
    View mView;
    @BindView(R.id.pullLoadMoreRecyclerView_main_fragment_circle)
    PullLoadMoreRecyclerView pullLoadMoreRecyclerViewMainFragmentCircle;
    @BindView(R.id.multiStateView_main_fragment_circle)
    MultiStateView multiStateViewMainFragmentCircle;
    private RecyclerView mRecyclerView;

    /**
     * 请求的页数
     */
    private int page = 1;

    //宝妈圈适配器
    Main_CircleAdapter main_circleAdapter;
    //宝妈圈数据集
    private List<MomCircleBean.DataEntity.Mam_circlesEntity> dataEntityList = new ArrayList<>();
    //宝妈圈每页的活动数据集合
    ArrayList<MomCircleBean.DataEntity.Mam_circlesEntity> mList;

    String circle_type;

    boolean type_bool;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_main_circle, container, false);
        ButterKnife.bind(this, mView);

        circle_type = getArguments().getString("circle_type");
        type_bool = getArguments().getBoolean("type_bool");

        init();
        return mView;
    }

    public static final Main_CircleFragment Instance(String type, boolean bool) {
        Main_CircleFragment main_circleFragment = new Main_CircleFragment();
        Bundle bundle = new Bundle();
        bundle.putString("circle_type", type);
        bundle.putBoolean("type_bool", bool);
        main_circleFragment.setArguments(bundle);
        return main_circleFragment;
    }

    private void init() {
        multiStateViewMainFragmentCircle.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getMain_FriendCircleData(1, 10);
                    }
                });
        //获取首页朋友圈
        getMain_FriendCircleData(1, 10);

        //获取mRecyclerView对象
        mRecyclerView = pullLoadMoreRecyclerViewMainFragmentCircle.getRecyclerView();
        //代码设置scrollbar无效？未解决！
        mRecyclerView.setVerticalScrollBarEnabled(true);
//        设置下拉刷新是否可见
        pullLoadMoreRecyclerViewMainFragmentCircle.setRefreshing(false);
//        设置是否可以下拉刷新
        pullLoadMoreRecyclerViewMainFragmentCircle.setPullRefreshEnable(false);
        //设置是否可以上拉刷新
        //pullLoadMoreRecyclerViewMainFragmentCircle.setPushRefreshEnable(false);
        //显示下拉刷新
        pullLoadMoreRecyclerViewMainFragmentCircle.setRefreshing(true);
        //设置上拉刷新文字
        pullLoadMoreRecyclerViewMainFragmentCircle.setFooterViewText("正在加载···");
        //设置上拉刷新文字颜色
        //pullLoadMoreRecyclerViewMainFragmentCircle.setFooterViewTextColor(R.color.white);
        //设置加载更多背景色
        //pullLoadMoreRecyclerViewMainFragmentCircle.setFooterViewBackgroundColor(R.color.colorBackground);
        pullLoadMoreRecyclerViewMainFragmentCircle.setLinearLayout();

        main_circleAdapter = new Main_CircleAdapter(getActivity(), dataEntityList, type_bool);
        pullLoadMoreRecyclerViewMainFragmentCircle.setAdapter(main_circleAdapter);

        pullLoadMoreRecyclerViewMainFragmentCircle.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
                getMain_FriendCircleData(++page, 10);
            }
        });

        main_circleAdapter.setItemClickListener(new Main_CircleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getActivity(), CircleDetailsActivity.class);
                intent.putExtra("fcid", dataEntityList.get(position).getFcid()+"");
                startActivityForResult(intent, TAG_CIRCLE);
            }

            @Override
            public void onZanClick(int fc_id, int position) {
                if (getJudgeLogin()){
                    getFabulousCircle(fc_id + "", position);
                }
            }

            @Override
            public void onGuanZhuClick(String followusercode, int position) {
                MobclickAgent.onEvent(getContext(),"MotherDynamicPayAttentionTo");//宝妈动态-关注
                if (getJudgeLogin()){
                    getGuanZhuCircle(followusercode, position);
                }
            }

            @Override
            public void onMSGClick(int fc_id, int position) {
                Intent mIntent = new Intent(getActivity(), FriendMSGActivity.class);
                mIntent.putExtra(HttpKey.Friend_MSG_friendcode, dataEntityList.get(position).getUsercode());
                startActivityForResult(mIntent, TAG_CIRCLE);
            }
        });
    }

    /**
     * 获取首页朋友圈数据
     *
     * @param indexpage
     * @param pagesize
     * @return
     */
    public void getMain_FriendCircleData(int indexpage, int pagesize) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.MOM_FC_usercode, ForPreference.getString(ForContents.USER_PHONE).equals("") ||
                ForPreference.getString(ForContents.USER_PHONE) == null ? "1" : ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.MOM_FC_current, indexpage + "");
        formMap.put(HttpKey.MOM_FC_pagesize, pagesize + "");
        formMap.put(HttpKey.MOM_FC_circle_type, circle_type);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.GetMamCirclePage, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "getMain_FriendCircleData", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        MomCircleBean bean = new Gson().fromJson(response, MomCircleBean.class);

                        mList = new ArrayList<MomCircleBean.DataEntity.Mam_circlesEntity>();
                        mList = (ArrayList<MomCircleBean.DataEntity.Mam_circlesEntity>) bean.getData().getMam_circles();

                        if (mList != null && mList.size() > 0) {
                            if (page == 1) {
                                dataEntityList.clear();
                                dataEntityList.addAll(mList);
                                //刷新数据
                                main_circleAdapter.addAllData(dataEntityList);
                                pullLoadMoreRecyclerViewMainFragmentCircle.setPullLoadMoreCompleted();
                            } else {
                                //加载更多
                                dataEntityList.addAll(mList);
                                main_circleAdapter.addAllData(dataEntityList);
                                pullLoadMoreRecyclerViewMainFragmentCircle.setPullLoadMoreCompleted();
                            }
                            multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (page == 1) {
                                multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            } else {
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        ForToast.showToast(R.string.error_down_end);
                                        //刷新数据
                                        main_circleAdapter.notifyDataSetChanged();
                                        pullLoadMoreRecyclerViewMainFragmentCircle.setPullLoadMoreCompleted();
                                    }
                                }, 1000);
                                multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            }
                        }
                    } else {
                        multiStateViewMainFragmentCircle.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 点赞
     */
    private void getFabulousCircle(final String fcid, final int position) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.FC_PRAISE_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.FC_PRAISE_FCID, fcid);
        formMap.put(HttpKey.FC_PRAISE_TYPE, "2");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_CIRCLE_PRAISE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        int num = dataEntityList.get(position).getPraisenumber();
                        if (dataEntityList.get(position).getPraisestate() == 1) {
                            dataEntityList.get(position).setPraisestate(0);
                            dataEntityList.get(position).setPraisenumber(--num);
                        } else {
                            dataEntityList.get(position).setPraisestate(1);
                            dataEntityList.get(position).setPraisenumber(++num);
                        }
                        main_circleAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 关注朋友
     */
    public void getGuanZhuCircle(final String followusercode, final int position) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Follow_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Follow_followusercode, followusercode);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.FRIEND_MSG_follow, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        int date = Integer.parseInt(jsonObject.getString("data"));
                        for (int i = 0; i < dataEntityList.size(); i++) {
                            if (dataEntityList.get(i).getUsercode().equals(followusercode)) {
                                dataEntityList.get(i).setFollow(date);
                            }
                        }

                        Web_forum_changeBean web_forum_changeBean = new Web_forum_changeBean(0,0,0,new ArrayList<Web_Focus>(),0);

                        int follow = ForPreference.getInt(ForContents.USER_follow);//关注数
                        switch (date) {
                            case 1:
                                ForPreference.putInt(ForContents.USER_follow, ++follow);
                                web_forum_changeBean.getWebFocusList().add(new Web_Focus(1,dataEntityList.get(position).getUsercode()));
                                break;
                            case 2:
                                ForPreference.putInt(ForContents.USER_follow, --follow);
                                web_forum_changeBean.getWebFocusList().add(new Web_Focus(2,dataEntityList.get(position).getUsercode()));
                                break;
                            case 3:
                                ForPreference.putInt(ForContents.USER_follow, ++follow);
                                web_forum_changeBean.getWebFocusList().add(new Web_Focus(3,dataEntityList.get(position).getUsercode()));
                                break;
                        }
                        ((MainActivity) getActivity()).getMainFragmentRefreshGuanzhu(false , web_forum_changeBean);
                        ((MainActivity) getActivity()).textViewRightFollow.setText(ForPreference.getInt(ForContents.USER_follow) + "");//设置关注数量
                        main_circleAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                //获取首页朋友圈
//                getMain_FriendCircleData(1, 10);
                ForLog.i(TAG,"2");
            }
        }
    }

    public void getRefreshDate(Web_forum_changeBean web_forum_changeBean){
        if (web_forum_changeBean.getWebFocusList() != null){
            if (web_forum_changeBean.getWebFocusList().size() > 0) {
                for (int i = 0; i < web_forum_changeBean.getWebFocusList().size(); i++) {
                    for (int j = 0; j < dataEntityList.size(); j++) {
                        if (web_forum_changeBean.getWebFocusList().get(i).getFollowusercode().
                                equals(dataEntityList.get(j).getUsercode())) {
                            dataEntityList.get(j).setFollow(web_forum_changeBean.getWebFocusList().get(i).getFocusNum());
                        }
                    }
                }
            }
        }

        main_circleAdapter.notifyDataSetChanged();
    }

}
